package com.stps.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.stps.factory.ServiceFactory;
import com.stps.vo.TextBook;

/**
 * Servlet implementation class TextBookBuyServlet
 */
@WebServlet("/TextBookBuyServlet")
public class TextBookBuyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TextBookBuyServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");

		String crud = request.getParameter("crud");
		System.out.println("crud: " + crud);

		JSONObject jsonObj = new JSONObject();
		TextBook TextBook = new TextBook();
		TextBook.setId(Integer.valueOf(request.getParameter("id")));
		try {
			TextBook.setName(ServiceFactory.getTextBookServiceFactory().get(Integer.valueOf(request.getParameter("id"))).getName());
		} catch (NumberFormatException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		} catch (Exception e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		try {
			if(Integer.valueOf(ServiceFactory.getTextBookServiceFactory().get(Integer.valueOf(request.getParameter("id"))).getNum()) - Integer.valueOf(request.getParameter("num")) > 0) {
				TextBook.setNum(Integer.valueOf(ServiceFactory.getTextBookServiceFactory().get(Integer.valueOf(request.getParameter("id"))).getNum()) - Integer.valueOf(request.getParameter("num")));
			}else {
				jsonObj.put("code", -1);
				jsonObj.put("msg", "书籍定购失败,您的定购数量超出了教材库中的数量");
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}//数据库中原有的数量减去提交的数量
		try {
			if (ServiceFactory.getTextBookServiceFactory().update(TextBook)) {
				jsonObj.put("code", 0);
				jsonObj.put("msg", "书籍购买成功！会在七日内送到指定地址！");
			} else {
				jsonObj.put("code", -1);
				jsonObj.put("msg", "书籍定购失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(jsonObj.toJSONString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
